//
//  TSBaseTableViewController.swift
//  TSProfitProject
//
//  Created by TmmmS on 2019/10/29.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit
import DZNEmptyDataSet

class TSBaseTableViewController: UITableViewController {

    var emptyAlertImage : UIImage? = nil
    var emptyAlertText : String? = nil
    var emptyAlertOffset : CGFloat = 0
    var shouldDisplayEmptyAlert : Bool = true
    var customEmptyView : UIView? = nil
    var alertParagraphStyle : NSMutableParagraphStyle!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if #available(iOS 11.0, *) {
            self.tableView.contentInsetAdjustmentBehavior = .never
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        
        alertParagraphStyle = (NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle)
        alertParagraphStyle.lineSpacing = 4
        alertParagraphStyle.alignment = .center
        
        tableView.emptyDataSetSource = self
        tableView.emptyDataSetDelegate = self
    }

}

extension TSBaseTableViewController : DZNEmptyDataSetSource {
    
    internal func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        if let emptyImg = emptyAlertImage {
            return emptyImg
        } else {
            return nil
        }
    }
    
    internal func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {

        let attributes = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 15), NSAttributedString.Key.foregroundColor:UIColor.hexadecimalColor(hexadecimal: "#999999")]
        return NSAttributedString.init(string: emptyAlertText ?? "暂无数据", attributes: attributes)
    }
    
    internal func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
        return emptyAlertOffset
    }
    
    func customView(forEmptyDataSet scrollView: UIScrollView!) -> UIView! {
        
        if customEmptyView != nil {
            let view = customEmptyView!
            let heightConstraint = NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: SCREEN_HEIGHT)
            view.addConstraint(heightConstraint)
            
            return view
        }
        return nil;
    }
}

extension TSBaseTableViewController : DZNEmptyDataSetDelegate {
    
    internal func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool {
        return self.shouldDisplayEmptyAlert
    }
    
    internal func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool {
        return true
    }

}

